package com.design.pattern.prototype.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Field;

/**
 * @version 1.0
 * @author: CRM_SYSTEM
 * @date: 2022/9/16 0:11
 * @Description:
 */
public class CopyUtils {

    //浅拷贝
    public static <T> T copy(T t){
        Class<?> clazz = t.getClass();
       T result=null;
        try {
            result= (T) clazz.newInstance();

            for (Field field : clazz.getDeclaredFields()) {
                field.setAccessible(true);
                field.set(result,field.get(t));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    //深拷贝
    public  static <T> T deepCopy(T t){
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(t);

            ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
            ObjectInputStream ois = new ObjectInputStream(bis);
           return (T) ois.readObject();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}
